package com.zhm.demo;

import com.zhm.demo.bean.TestBean2;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

//@Component
public class TestBeanComponent {

    @Resource
    private ApplicationContext applicationContext;



    @PostConstruct
    public void init(){


        new Thread(() -> {
            while (true) {

                String beanName = "testBean2";

                BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) applicationContext;

                if(beanFactory.containsBeanDefinition(beanName)) {
                    beanFactory.removeBeanDefinition(beanName);
                }


                GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
                beanDefinition.setBeanClass(TestBean2.class);
                beanFactory.registerBeanDefinition(beanName, beanDefinition);


                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                TestBean2 bean = applicationContext.getBean(TestBean2.class);
                System.out.println(bean);
                bean.setStr("1231");
            }
        }).start();
    }
}
